let express = require('express');
var jwt = require('jsonwebtoken');

// 工具包
const { createRes } = require('../utils/index');
let { checkUser, getUserInfo, regist, updataUser } = require('../model/userManage');
let { error, success, jwtInfo } = require('./guide/prompt');
const { cache } = require('ejs');
let router = express.Router();


// 用户登录--检测帐号密码是否正确
router.post('/checkUser', async function (req, res, next) {
  let { username, password } = req.body
  let data = await checkUser(username, password)
  if (data) {
    let token = jwt.sign({ username: username }, jwtInfo.primary, { expiresIn: '2h' });
    res.send(createRes(200, success.user, { token }))
  } else {
    res.send(createRes(500, error.user))
  }
});

/**
 *  查询用户个人信息
 * 
 * **/
router.get('/getUserInfo', async function (req, res, next) {
  let { token } = req.query
  token = token ? token : ''

  try {
    let decoded = jwt.verify(token, jwtInfo.primary) // 如果超过token的时间 直接抛出异常
    if (decoded.username) {
      //  存在username 就通过username 去库里查找
      let data = await getUserInfo(decoded.username)
      if (data.length === 1) {
        // res.status(200).send({code: 200, data}) 两种写法
        res.send(createRes(200, success.userInfo, data[0]))
      } else {
        res.send(createRes(500, error.userInfo))
      }

    } else {
      res.send(createRes(500, error.userInfo))
    }
  } catch (err) {
    res.send(createRes(500, error.token))
  }
})


/**
 * 注册 regist
 * 
 * */
router.post('/regist', async function (req, res, next) {
  let { username, password, telephone, type } = req.body
  try {
    let data = await regist(username, password, telephone, type)
    if (data) {
      res.send(createRes(200, success.regist))
    } else {
      res.send(createRes(500, error.regist))
    }
  } catch (error) {
    res.send(createRes(500, error.regist))
  }

})

/**
 * 修改用户信息
 * 
*/

router.post('/updataUser', async function (req, res, next) {
  let { username, password, telephone, type } = req.body

  try {
    let data = await updataUser(username, password, telephone, type)
    if (data) {
      res.send(createRes(200, success.updata))
    } else {
      res.send(createRes(500, error.updata))

    }

  } catch (error) {
    res.send(createRes(500, error.updata))
  }
})


router.post('/loginout', async function (req, res,next) {

  res.send(createRes(200, success.loginout))
  // let { token } = req.query
  // token = token ? token : ''
  // try {
  //   // let decoded = jwt.verify(token, jwtInfo.primary) // 如果超过token的时间 直接抛出异常
  // } catch (error) {
    
  // }

})

module.exports = router;
